' PicBasic Pro SPI slave program (see SPImast.bas for connections)


' Allocate RAM
dataout	VAR     BYTE[8]			'Data out array

SSPEN	VAR		SSPCON.5		'SSP Enable bit
CKP		VAR		SSPCON.4		'Clock Polarity Select
SMP		VAR		SSPSTAT.7		'Data input sample phase
CKE		VAR		SSPSTAT.6		'Clock Edge Select bit
SSPIF	VAR		PIR1.3			'interrupt flag - last bit set

i		VAR		BYTE			'loop counter
a		VAR		BYTE[6]			'Holds 6 characters of data


		TRISC = %11011111		'set PORTC I/O
		SSPCON = %00000101		'configure SPI slave, no SS
		
		CKP = 0					'clock idle low
		CKE = 0					'transmit on idle to active transition
		SSPIF = 0				'clear SPI interrupt
		SMP = 0					'sample in middle of data

        ADCON1 = $0e			'PORTA.0 analog, rest PORTA and PORTE pins to digital

        dataout[0] = "A"		'Preset output data to "ADC= "
        dataout[1] = "D"
        dataout[2] = "C"
        dataout[3] = "="
        dataout[4] = " "

loop:	SSPEN = 0				'disable/enable SSP to reset port
		SSPEN = 1
		GoSub letclear			'wait for byte received
		IF (SSPBUF <> "?") Then loop	'wait for ? to start conversion
		
		ADCIN 0, dataout[5]		'Read ADC channel 0, store in 6th position of string
		
		GoSub senddata			'send "!" and string of data
				
		GoTo loop				'do it forever
		

senddata:
		GoSub letclear			'wait until buffer ready
		SSPBUF = "!"			'send reply

		For i = 0 to 5			'loop for 6 array locations
			GoSub letclear		'wait until buffer ready
			SSPBUF = dataout[i]	'send array variable
		Next i					'next location
		
		Return

		
letclear:
		IF SSPIF = 0 Then letclear	'wait for interrupt flag
		SSPIF = 0				'reset flag

		Return
		




